package cn.wolfcode.p2p.base.service.impl;
import cn.wolfcode.p2p.anno.CheckDataSource;
import cn.wolfcode.p2p.base.domain.IpLog;
import cn.wolfcode.p2p.base.domain.LoginInfo;
import cn.wolfcode.p2p.base.mapper.IpLogMapper;
import cn.wolfcode.p2p.base.query.QueryObject;
import cn.wolfcode.p2p.base.service.IIpLogService;
import cn.wolfcode.p2p.util.Constant;
import cn.wolfcode.p2p.util.PageResult;
import cn.wolfcode.p2p.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class IpLogServiceImpl implements IIpLogService {
    @Autowired
    private IpLogMapper ipLogMapper;

    @Override
    public void save(LoginInfo loginInfo,int state,int userType) {
        if (loginInfo != null) {
            IpLog ipLog = new IpLog();
            ipLog.setIp(UserContext.getIp());
            ipLog.setUsername(loginInfo.getUsername());
            ipLog.setLoginTime(new Date());
            ipLog.setState(state);
            if(userType == LoginInfo.TYPE_WEBSITE){
                ipLog.setUserType(LoginInfo.TYPE_WEBSITE);
            }else{
                ipLog.setUserType(LoginInfo.TYPE_MGRSITE);
            }
            ipLogMapper.insert(ipLog);
        }
    }

    @CheckDataSource(Constant.SLAVE)
    @Override
    public PageResult query(QueryObject qo) {
        int count = ipLogMapper.queryForCount(qo);
        if (count == 0) {
            return PageResult.empty(qo.getPageSize());
        }
        int totalPage = count % qo.getPageSize() == 0 ? count / qo.getPageSize() : count / qo.getPageSize() + 1;
        if(totalPage < qo.getCurrentPage()){
            qo.setCurrentPage(totalPage);
        }
        List<IpLog> listData = ipLogMapper.queryForList(qo);
        return new PageResult(listData,count,qo.getCurrentPage(),qo.getPageSize());
    }
}
